package controllers

import (
	"net/url"
	"os"
	"net/http"
	"path/filepath"
)

type TestParams struct {
	ToPath string `form:"to"`
};

// @router /testResponse.php [Post]
// @binding controllers.TestParams
func TestResponse(params TestParams, res http.ResponseWriter, req *http.Request) string {

	if params.ToPath != "" {
		to, err := url.QueryUnescape(params.ToPath)
		if err != nil {
			res.WriteHeader(501)
			return "1"
		}

		files := req.MultipartForm.File
		fi, err := os.Stat(to)

		if ((err == nil || os.IsExist(err)) && fi.IsDir()) || len(files) == 0 {
			res.WriteHeader(502)
			return "1"
		}else {
			if (err == nil || os.IsExist(err)) && !fi.IsDir() {
				os.Remove(to)
			}

			dirpath := filepath.Dir(to)
			_, err := os.Stat(dirpath)

			if os.IsNotExist(err) {
				err = os.MkdirAll(dirpath, 0777)
				if err != nil {
					res.WriteHeader(503)
					return "1"
				}
			}

			fileHeader := files["file"][0]
			upfile, err := fileHeader.Open()
			defer upfile.Close()

			if err != nil {
				res.WriteHeader(504)
				return "1"
			}

			_, err = moveUploadFile(to, upfile)
			if err != nil {
				res.WriteHeader(505)
				return "1"
			}
		}
		return "0"
	}else {
		return `I\'m ready for that, you know.`
	}
}
